package com.ama.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 按照当天时间获取规则编号
 * “字母”+date+“001”
 */
public class GetNumber {
    /**
     * 获取一个规则的 单据编号
     * 按照当天时间获取规则编号
     * “字母”+date+“001”
     * @return
     * @param title xxx前缀
     * @param tableName 表名
     */
    public static String getDocumentNumber(String title,String tableName){
        String date = DateUtil.getTodayShort();
        String documentNum=title+date;
        Connection connection = JDBCutils.getConnection();
        PreparedStatement prst = null;
        ResultSet rs = null;
        String columnName = tableName+"_num";
        try{
            String sql = "select " + columnName+ " from " + tableName +" where "+ columnName + " like '"+title+date+"%' order by "+ columnName + " desc";
            prst = connection.prepareStatement(sql);
            rs = prst.executeQuery();
            if(rs.next()){
                int intNumber =  Integer.parseInt(rs.getString(1).substring(11));
                intNumber++;
                String Number = String.valueOf(intNumber);
                for (int i = 0; i < 3; i++){
                    Number = Number.length() < 3 ? "0" + Number : Number;
                }
                System.out.println(documentNum+Number);
                return documentNum+Number;
            }else {
                System.out.println(documentNum+"001");
                return documentNum+"001";
            }
        }catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("获取单据编号出现异常");
        }finally {
            JDBCutils.relieve(connection,prst,rs);
        }

    }
}
